import pymysql

def db_util(sql):

    try:
        conn = pymysql.connect(host="localhost", port=3306, user="root", password="zxc123!!", database="test_7_11",charset="utf8")
        cursor = conn.cursor()

        if sql.split()[0].lower() == "select":
            cursor.execute(sql)
            res = cursor.fetchall()
            # print(res)
            return res
        else:
            cursor.execute(sql)
            conn.commit()
            return conn.affected_rows()
    except Exception as e:
        conn.rollback()
        return str(e)
    finally:
        cursor.close()
        conn.close()

if __name__ == '__main__':
    result1 = db_util("select * from t_book")
    print(result1)
    result2 = db_util("insert into t_book(title, pub_date) values ('哈哈哈','1986-12-01')")
    print(result2)
